<template>
  <div>
    <div style="display: flex; align-items: center; margin-bottom: 16px;">
      <a-space>
        <a-dropdown>
          <template #overlay>
            <a-menu @click="handleMenuClick">
              <a-menu-item key="1">列表图</a-menu-item>
              <a-menu-item key="2">拓扑图</a-menu-item>
            </a-menu>
          </template>
          <a-button>
            视角切换
            <DownOutlined />
          </a-button>
        </a-dropdown>
      </a-space>
    </div>
    <!-- 拓扑关系图片 -->
    <div style="text-align: center; padding: 20px;">
      <img 
        src="/topology-diagram.png" 
        alt="Multi-Cluster Topology Relationships"
        style="max-width: 25%; height: auto;"
      />
    </div>
    <div class="topology-root">
      <!-- 集群卡片区 -->
      <div class="core-cluster-area" ref="coreClusterAreaRef">
        <ClusterTopology
          clusterType="core"
          @coreCard-mounted="onCoreCardMounted"
        />
      </div>
      <div class="edge-cluster-area" ref="edgeClusterAreaRef">
        <fakeCluster 
          @edgeCard-mounted="onEdgeCardMounted"
        />
      </div>
      <!-- 连线区（SVG 覆盖在卡片区上） -->
      <svg class="topology-svg" :width="svgWidth" :height="svgHeight">
        <line
          v-for="(edge, idx) in edges"
              :key="idx"
              :x1="getEdgePoint(edge.source, edge.sDirection).x"
              :y1="getEdgePoint(edge.source, edge.sDirection).y"
              :x2="getEdgePoint(edge.target, edge.tDirection).x"
              :y2="getEdgePoint(edge.target, edge.tDirection).y"
              :stroke="getLineColor(edge.edgesType)"
              stroke-width="3"
              marker-end="url(#arrow)"
        />
      </svg>
    </div>    
  </div>
</template>

<script setup lang="ts">

import router from "@/router";
import { ref, reactive, nextTick } from 'vue'
import ClusterTopology from '@/components/cluster/ClusterTopology.vue'
import fakeCluster from "@/components/cluster/fakeCluster.vue";
import { DownOutlined } from '@ant-design/icons-vue';
import type { MenuProps } from 'ant-design-vue';

const svgWidth = ref(1200)
const svgHeight = ref(600)
const coreClusterAreaRef = ref<HTMLElement | null>(null)
const edgeClusterAreaRef = ref<HTMLElement | null>(null)
const coreCardEls = ref<HTMLElement[]>([])
const edgeCardEls = ref<HTMLElement[]>([])

// edges: [卡片id, 卡片id]，后续你可以动态维护
const edges = ref<Edge[]>([
])

interface Edge {
  source: string
  sDirection: 'top' | 'bottom' | 'left' | 'right'
  target: string
  tDirection: 'top' | 'bottom' | 'left' | 'right'
  edgesType: string
}

// MultiCluster 组件内每个卡片渲染时 emit('card-mounted', {id, el})
function onCoreCardMounted(payload: {cardEls:HTMLElement[]}) {
  console.log('收到卡片列表', payload.cardEls)
  coreCardEls.value = payload.cardEls
  nextTick(() => {
    // 构造核心云间的edge
  })
}

// 处理边缘云集群的回调函数
function onEdgeCardMounted(payload: {cardEls:HTMLElement[]}) {
  edgeCardEls.value = payload.cardEls
  // const cardEl = cardEls.value.find(el => el.dataset.id === "101")
  // console.log('收到卡片列表1', payload.cardEls)
  // console.log('cardEl', cardEl)
  // 构造 edge
  nextTick(() => {
    // 等待 coreCardEls 有值
    if (!coreCardEls.value.length) {
      // 如果还没有，延迟再试
      setTimeout(() => {
        const coreId = coreCardEls.value[0]?.dataset.id
        console.log('coreId', coreId)
        edges.value = edgeCardEls.value
          .filter(edgeEl => edgeEl.dataset.id) // 过滤掉没有 id 的元素
          .map(edgeEl => ({
            source: coreId as string,
            sDirection: 'bottom',
            target: edgeEl.dataset.id as string, // 明确断言为 string
            tDirection: 'top',
            edgesType: 'success'
          }))
        console.log('edges', edges)
        // ...后续逻辑
        // 构造边和边 云间的edge
      }, 100)
      return 
    }
  })
}

function getEdgePoint(cardId: string, direction: string) {
  // 先找到对应的 DOM
  let cardEl = edgeCardEls.value.find(el => el.dataset.id === cardId)
  if (!cardEl) {
    cardEl = coreCardEls.value.find(el => el.dataset.id === cardId)
    if (!cardEl) {
      return { x: 0, y: 0 }
    }
  }
  const rect = cardEl.getBoundingClientRect()
  const areaRect = coreClusterAreaRef.value?.getBoundingClientRect() || { left: 0, top: 0 }

  switch (direction) {
    case 'top':
      return { x: rect.left - areaRect.left + rect.width / 2, y: rect.top - areaRect.top }
    case 'bottom':
      return { x: rect.left - areaRect.left + rect.width / 2, y: rect.top - areaRect.top + rect.height }
    case 'left':
      return { x: rect.left - areaRect.left, y: rect.top - areaRect.top + rect.height / 2 }
    case 'right':
      return { x: rect.left - areaRect.left + rect.width, y: rect.top - areaRect.top + rect.height / 2 }
    default:
      return { x: rect.left - areaRect.left + rect.width / 2, y: rect.top - areaRect.top + rect.height / 2 }
  }
}

function getLineColor(type: string) {
  switch (type) {
    case 'success': return '#46C37B'
    case 'info': return '#4A9BFF'
    case 'warning': return '#f0a63a'
    case 'danger': return '#c94d3c'
    default: return '#aaa'
  }
}

const handleMenuClick: MenuProps['onClick'] = e => {
  console.log('click', e);
  if (e.key === "1") {
    // 集群列表 - 跳转到当前页面
    router.push({ name: 'cluster' });
  } else if (e.key === "2") {
    // 集群拓扑 - 跳转到新页面
    router.push('/cluster-topology');
  }
};

</script>

<style scoped>
.topology-root {
  position: relative;
  width: 1200px;
  height: 600px;
  margin: 0 auto;
}
.core-cluster-area {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  /* 可选：设置高度和 margin-top 让其在页面垂直居中 */
  margin-top: 60px;
}
.edge-cluster-area {
  display: flex;
  position: relative;
  justify-content: center;
  margin-top: 60px;
  z-index: 1;
}
.topology-svg {
  position: absolute;
  left: 0; top: 0;
  width: 100%; height: 100%;
  pointer-events: none;
  z-index: 2;
}
</style> 